package com.elh.lock;

import com.elh.lock.container.TheadWaitContainer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.TimeUnit;

/**
 * @author liulei
 **/
@Slf4j
public class RedisFairDistributeLock implements IFairDistributeLock {

    @Autowired
    private TheadWaitContainer theadWaitContainer;

    @Override
    public boolean lock(String key, long timeOut, TimeUnit timeUnit) {
        Thread currentThread = Thread.currentThread();
        theadWaitContainer.addWaitContainer(key,currentThread);
        long millTimeOut = TimeUnit.MILLISECONDS.convert(timeOut, timeUnit);
        while((millTimeOut) < System.currentTimeMillis()){
            Thread thread = theadWaitContainer.signWaitContainer(key);
            if(thread.equals(currentThread)){
                return true;
            }
            try {
                TimeUnit.MILLISECONDS.sleep(200);
            } catch (InterruptedException e) {
                log.warn(e.getMessage(),e);
            }
        }
        return false;
    }

}
